<?php
namespace User\Controller;

use Common\Controller\MemberbaseController;

class ProfileController extends MemberbaseController {
	
	function _initialize(){
		parent::_initialize();
		$this->assign($this->user);  
	}
	
    // 编辑用户资料
	public function edit() {
		$this->assign($this->user);
    	$this->display();
    }
    
    // 编辑用户资料提交
    public function edit_post() {
    	if(IS_POST){
    		$_POST['id']=$this->userid;
    		if ($this->users_model->field('id,user_nicename,sex,birthday,user_url,signature')->create()!==false) {
				if ($this->users_model->save()!==false) {
					$this->user=$this->users_model->find($this->userid);
					sp_update_current_user($this->user);
					$this->success("保存成功！",U("user/profile/edit"));
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->users_model->getError());
			}
    	}
    	
    }
    
    // 个人中心修改密码
    public function password() {
		$this->assign($this->user);
    	$this->display();
    }
    
    // 个人中心修改密码提交
    public function password_post() {
    	if (IS_POST) {
    	    $old_password=I('post.old_password');
    		if(empty($old_password)){
    			$this->error("原始密码不能为空！");
    		}
    		
    		$password=I('post.password');
    		if(empty($password)){
    			$this->error("新密码不能为空！");
    		}
    		
    		$uid=sp_get_current_userid();
    		$admin=$this->users_model->where(array('id'=>$uid))->find();
    		if(sp_compare_password($old_password, $admin['user_pass'])){
    			if($password==I('post.repassword')){
    				if(sp_compare_password($password, $admin['user_pass'])){
    					$this->error("新密码不能和原始密码相同！");
    				}else{
    					$data['user_pass']=sp_password($password);
    					$data['id']=$uid;
    					$r=$this->users_model->save($data);
    					if ($r!==false) {
    						$this->success("修改成功！");
    					} else {
    						$this->error("修改失败！");
    					}
    				}
    			}else{
    				$this->error("密码输入不一致！");
    			}
    	
    		}else{
    			$this->error("原始密码不正确！");
    		}
    	}
    	 
    }
    
    // 第三方账号绑定
    public function bang(){
    	$oauth_user_model=M("OauthUser");
    	$uid=sp_get_current_userid();
    	$oauths=$oauth_user_model->where(array("uid"=>$uid))->select();
    	$new_oauths=array();
    	foreach ($oauths as $oa){
    		$new_oauths[strtolower($oa['from'])]=$oa;
    	}
    	$this->assign("oauths",$new_oauths);
    	$this->display();
    }
    
    // 用户头像编辑
    public function avatar(){
		$this->assign($this->user);
    	$this->display();
    }
    
    // 用户头像上传
    public function avatar_upload(){
    	$config=array(
			'rootPath' => './'.C("UPLOADPATH"),
			'savePath' => './avatar/',
			'maxSize' => 512000,//500K
			'saveName'   =>    array('uniqid',''),
			'exts'       =>    array('jpg', 'png', 'jpeg'),
			'autoSub'    =>    false,
    	);
    	$upload = new \Think\Upload($config,'Local');//先在本地裁剪
    	$info=$upload->upload();
    	//开始上传
    	if ($info) {
    	//上传成功
    	//写入附件数据库信息
    		$first=array_shift($info);
    		$file=$first['savename'];
    		session('avatar',$file);
    		$this->ajaxReturn(sp_ajax_return(array("file"=>$file),"上传成功！",1),"AJAX_UPLOAD");
    	} else {
    		//上传失败，返回错误
    		$this->ajaxReturn(sp_ajax_return(array(),$upload->getError(),0),"AJAX_UPLOAD");
    	}
    }
    
    // 用户头像裁剪
    public function avatar_update(){
        $session_avatar=session('avatar');
    	if(!empty($session_avatar)){
    		$targ_w = I('post.w',0,'intval');
    		$targ_h = I('post.h',0,'intval');
    		$x = I('post.x',0,'intval');
    		$y = I('post.y',0,'intval');
    		$jpeg_quality = 90;
    		
    		$avatar=$session_avatar;
    		$avatar_dir=C("UPLOADPATH")."avatar/";
    		
    		$avatar_path=$avatar_dir.$avatar;
    		
    		$image = new \Think\Image();
    		$image->open($avatar_path);
    		$image->crop($targ_w, $targ_h,$x,$y);
    		$image->save($avatar_path);
    		
    		$result=true;
    		
    		$file_upload_type=C('FILE_UPLOAD_TYPE');
    		if($file_upload_type=='Qiniu'){
    		    $upload = new \Think\Upload();
    		    $file=array('savepath'=>'','savename'=>'avatar/'.$avatar,'tmp_name'=>$avatar_path);
    		    $result=$upload->getUploader()->save($file);
    		}
    		if($result===true){
    		    $userid=sp_get_current_userid();
    		    $result=$this->users_model->where(array("id"=>$userid))->save(array("avatar"=>'avatar/'.$avatar));
    		    session('user.avatar','avatar/'.$avatar);
    		    if($result){
    		        $this->success("头像更新成功！");
    		    }else{
    		        $this->error("头像更新失败！");
    		    }
    		}else{
    		    $this->error("头像保存失败！");
    		}
    		
    	}
    }
    
    // 保存用户头像
    public function do_avatar() {
		$imgurl=I('post.imgurl');
		//去'/'
		$imgurl=str_replace('/','',$imgurl);
		$old_img=$this->user['avatar'];
		$this->user['avatar']=$imgurl;
		$res=$this->users_model->where(array("id"=>$this->userid))->save($this->user);		
		if($res){
			//更新session
			session('user',$this->user);
			//删除旧头像
			sp_delete_avatar($old_img);
		}else{
			$this->user['avatar']=$old_img;
			//删除新头像
			sp_delete_avatar($imgurl);
		}
		$this->ajaxReturn($res);
	}      

	//地址管理
	public function address(){
		$model = M('UserAddress');
        $address_list = $model->where('user_id = '.$this->userid)->order("is_default desc")->select();
        if($address_list){
        	$area_id = array();
        	foreach ($address_list as $val){
        		$area_id[] = $val['province'];
                        $area_id[] = $val['city'];
                        $area_id[] = $val['district'];
                        $area_id[] = $val['twon'];                        
        	}    
            $area_id = array_filter($area_id);
        	$area_id = implode(',', $area_id);
        	$regionList = M('address')->where("id in ($area_id)")->getField('id,name');
        	$this->assign('regionList', $regionList);
        }
        
        $this->assign($this->user);             
        $this->assign('address_list', $address_list);
		$this->display();
	}
	
	//默认地址
	public function default_address(){
		$id = I('get.id');
		if(!empty($id) && $id){
			$res = M('UserAddress')->where(array('user_id'=>$this->userid))->save(array('is_default'=>0)); 
			$res2 = M('UserAddress')->where(array('user_id'=>$this->userid,'address_id'=>$id))->save(array('is_default'=>1));
			if($res !== false && $res2 !== false){
				redirect(U('user/profile/address'));
			}else{
				$this->error('操作失败');
			}
		}
	}
	
	//添加编辑收货地址
	public function address_info(){
		$addressType = I('get.type');
		$this->address_id = $addressType;
		if($addressType == 'add'){
			$this->addAddress();
		}else{
			$this->editAddress();
		}
		
		$this->display();
	}
	
	//添加地址
	public function addAddress(){
		if(IS_POST){
			$data = I('post.');
			$data['user_id'] = $this->userid;
			$model = D('UserAddress');
			$count = $model->where(array('user_id'=>$this->userid))->count();
			$data['is_default'] = empty($count) ? 1 : 0; //没有地址就设为默认
			if($model->create() !== false){
				$address = $model->add($data);
				if($address){
					$result = array('status'=>1,'msg'=>'添加成功');
				}else{
					$result = array('status'=>-100,'msg'=>'添加失败');
				}
			}else{
				$this->error($model->getError());
			}
			exit(json_encode($result));
		}
		
		$province = M('address')->where(array('parent_id'=>0,'level'=> 1))->select();
        $this->assign('province',$province);
	}
	
	//编辑地址
	public function editAddress(){
		$address_mobel = M('address');
		$address = M('UserAddress')->where(array('address_id'=>$this->address_id,'user_id'=>$this->userid))->find();
		
		if(IS_POST){
			$data = I('post.');
			
			$model = D('UserAddress');
			if($model->create() !== false){
				$address = $model->where(array('address_id'=>I('post.address_id'),'user_id'=>$this->userid))->save($data);
				if($address !== false){
					$result = array('status'=>1,'msg'=>'保存成功');
				}else{
					$result = array('status'=>-100,'msg'=>'保存失败');
				}
			}else{
				$this->error($model->getError());
			}
			exit(json_encode($result));
		}
		$province = $address_mobel->where(array('level'=> 1))->select();
		$city = $address_mobel->where(array('parent_id'=>$address['province'],'level'=> 2))->select();
		$district = $address_mobel->where(array('parent_id'=>$address['city']))->select();
		//print_r($district);
		if($address['twon']){
        	$twon = M('address')->where(array('parent_id'=>$address['district'],'level'=>4))->select();
        	$this->assign('twon',$twon);
        }
		$this->assign('province',$province);
		$this->assign('city',$city);
		$this->assign('district',$district);
		$this->assign('address',$address);
	}
	
	//订单管理
	public function myorder(){		
		$count = M('GoodsOrder')->where(array('user_id'=>$this->userid))->count();
		$page = $this->page($count, 5);
		$order = M('GoodsOrder')->where(array('user_id'=>$this->userid))->limit($page->firstRow , $page->listRows)->order('add_time DESC')->select();
		$order_status = C('ORDER_STATUS'); //获取订单状态
		$pay_status = C('PAY_STATUS'); //获取支付状态
		
		foreach($order as $key=>$val){
			$list = M('GoodsOrderSub')->field('a.*,b.goods_img')
			->alias('a')
			->join('__GOODS__ b ON a.goods_id = b.goods_id')
			->where(array("order_id" => $val['order_id']))
			->select();
			$order[$key]['goods_list'] = $list;
		}
		//print_r($order);die;		
		$this->assign('order',$order);
		$this->assign('order_status',$order_status);
		$this->assign('pay_status',$pay_status);
		$this->assign('page', $page->show('Member'));
		$this->display();
		
	}
	
	//查看订单
	public function order_detail(){
		$order_id = I('get.order_id');
		$where = array('user_id'=>$this->userid,'order_id'=>$order_id,'is_del'=>0);
		$order = M('GoodsOrder')->where($where)->find();		
		if(empty($order)){
			$this->error('订单不存在');
		}
		//商品信息
		$order_goods = M('GoodsOrderSub')->field(array('a.*,b.goods_img',"(a.goods_num * a.member_goods_price)"=>"goods_total"))
			->alias('a')
			->join('__GOODS__ b ON a.goods_id = b.goods_id')
			->where(array("order_id" => $order_id))
			->select();
		$address = getAddressName($order['province'],$order['city'],$order['district']);
		$order['address_info'] = $address;
		
		//订单操作记录
		$log_where['order_id'] = $order_id;
		$log_where['status_desc'] = array(array('neq','cancel'),array('neq','pay'));		 
		$order_log = M('GoodsOrderLog')->group('status_desc')->where($log_where)->order('log_time ASC')->select();
				
		
		$this->assign('order',$order);
		$this->assign('order_goods',$order_goods);		
		$this->assign('order_log',$order_log);		
		$this->display();
	}
	
	//取消订单
	public function operate(){
		$order_id = I('id');
		$type = I('type');
		if($order_id && $type){
			switch($type){
				case 'invalid':
					$updata['order_status'] = 4;
					break;
				case 'receive':
					$updata['shipping_status'] = 2;
					break;
				default:
					 $this->error('未知错误！');
			}
			$result = M('GoodsOrder')->where("order_id = {$order_id}")->save($updata);
			if($result){
				$this->success('操作成功！');
			}else{
				 $this->error('未知错误！');
			}
		}else{
			 $this->error('未知错误！');
		}
	}
	
}